<?php


namespace app\common\cachemodel\privatearea;


use app\common\model\BaseCache;
use think\Log;
use XznsTools\cache\CacheManage;
use Exception;

class PrivateAreaGoods extends BaseCache
{
    protected $table = 'wechat_backup_07_18_14_43_00.private_area_goods';

    protected $cacheModel = 'privatearea.good';

    public $goodTypeName = [
        1 => '星盘',
        2 => '塔罗',
        3 => '疗愈调频',
        4 => '面相',
        5 => '骰子',
        6 => '实物商品',
    ];

    /**
     * 更新 商品链接信息
     * @param string $goodHash
     * @param int $lid
     * @param array $updataData
     * @return bool
     */
    public function updatePrivateAreaLinkData(string $goodHash, int $lid, array $updataData)
    {
        try
        {
            // 更新信息
            $this->table('wechat_backup_07_18_14_43_00.private_area_link')->where(['id' => $lid])->update($updataData);
            // 更新缓存信息
            CacheManage::getInstance()->setCacheConfig($this->cacheModel, $goodHash)->setCache($updataData);
            return true;
        }
        catch (Exception $e)
        {
            Log::write('私域H5 PrivateAreaGoods model 异常：' . $e->getMessage() . '失败行数：' . $e->getLine(), 'error');
            return false;
        }
    }

    /**
     * 缓存获取私域H5 商品信息
     * @param string $goodHash 商品hash
     * @param array $filed
     * @return array|bool|mixed
     * @throws Exception
     */
    public function getPrivateAreaGoodInfo(string $goodHash, array $filed = [])
    {
        $data = CacheManage::getInstance()->setCacheConfig($this->cacheModel, $goodHash)->getDataAndSet(function () use ($goodHash)
        {
            return $this->getPrivateAreaGoodInfoFromDms($goodHash);
        }, $filed);

        if (isset($data['extend']))
        {
            $data['extend'] = json_decode($data['extend'], true);
        }

        $data = arrayKeyData2int($data, ['uid', 'is_pay', 'gid', 'lid', 'type', 'card_num', 'info_type', 'create_time', 'channel_id']);

        return $data;
    }

    /**
     * 数据库获取私域H5 商品信息
     * @param string $goodHash
     * @return array|mixed
     */
    public function getPrivateAreaGoodInfoFromDms(string $goodHash)
    {
        try
        {
            $data = $this->alias('g')->join('wechat_backup_07_18_14_43_00.private_area_link l', 'l.gid=g.id')
                ->where(['hash' => $goodHash])
                ->field('l.id as lid,l.uid,l.gid,l.price,l.order_num,l.is_pay,l.channel_id,l.create_time,g.type,g.info_type,g.name,g.content,g.img,g.card_num,g.extend,l.aid')
                ->findOrFail()->toArray();
        }
        catch (Exception $e)
        {
            $data = [];
        }

        return $data;
    }
}
